package com.fan.cachewebview.core

import android.content.Context
import com.fan.cachewebview.utils.AppUtils
import com.fan.cachewebview.core.filter.MimeTypeFilterApi
import com.fan.cachewebview.core.filter.CacheMimeTypeFilter
import com.fan.cachewebview.utils.MemCalculator
import java.io.File

/**
 * @description webview缓存配置
 * @date: 2022/2/22 11:48
 * @author: fan
 */
class CacheConfig private constructor() {

    // 缓存路径
    private var mCacheDir: String? = null

    // 应用版本号
    private var mVersion = 0
    private var mDiskCacheSize: Long = 0
    private var mMemCacheSize = 0
    private var mFilter: MimeTypeFilterApi? = null
    fun getCacheDir(): String? {
        return mCacheDir
    }

    fun getVersion(): Int {
        return mVersion
    }

    fun setVersion(version: Int) {
        mVersion = version
    }

    fun getFilter(): MimeTypeFilterApi? {
        return mFilter
    }

    fun getDiskCacheSize(): Long {
        return mDiskCacheSize
    }

    fun getMemCacheSize(): Int {
        return mMemCacheSize
    }

    class Builder(context: Context) {
        private var cacheDir: String
        private var version: Int
        private var diskCacheSize = DEFAULT_DISK_CACHE_SIZE.toLong()
        private var memoryCacheSize: Int = MemCalculator.getSize()
        private var filter: MimeTypeFilterApi = CacheMimeTypeFilter()
        fun setCacheDir(cacheDir: String): Builder {
            this.cacheDir = cacheDir
            return this
        }

        fun setVersion(version: Int): Builder {
            this.version = version
            return this
        }

        fun setDiskCacheSize(diskCacheSize: Long): Builder {
            this.diskCacheSize = diskCacheSize
            return this
        }

        fun setExtensionFilter(filter: MimeTypeFilterApi): Builder {
            this.filter = filter
            return this
        }

        fun setMemoryCacheSize(memoryCacheSize: Int): Builder {
            this.memoryCacheSize = memoryCacheSize
            return this
        }

        fun build(): CacheConfig {
            val config = CacheConfig()
            config.mCacheDir = cacheDir
            config.mVersion = version
            config.mDiskCacheSize = diskCacheSize
            config.mFilter = filter
            config.mMemCacheSize = memoryCacheSize
            return config
        }

        companion object {
            private const val CACHE_DIR_NAME = "cache_webview"
            private const val DEFAULT_DISK_CACHE_SIZE = 100 * 1024 * 1024
        }

        init {
            cacheDir = context.cacheDir.toString() + File.separator + CACHE_DIR_NAME
            version = AppUtils.getVersionCode(context)
        }
    }
}